﻿using System;
using System.Collections.Concurrent;
using System.Threading;

namespace Utils
{
    public class NotifyHandler<K, T> where K : IEquatable<K>
    {
        private readonly ConcurrentDictionary<K, T> waitObject = new ConcurrentDictionary<K, T>();

        private readonly ConcurrentDictionary<K, ManualResetEvent> manualResetEvents = new ConcurrentDictionary<K, ManualResetEvent>();

        /// <summary>
        /// 等待一个结果
        /// </summary>
        /// <param name="key"></param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public bool WaitResult(K key, Action begin, out T result, int timeout = 3000)
        {
            var manualResetEvent = manualResetEvents.GetOrAdd(key, s => new ManualResetEvent(false));
            try
            {
                begin?.Invoke();
                if (manualResetEvent.WaitOne(timeout))
                {
                    if (waitObject.TryGetValue(key, out result))
                    {
                        return true;
                    }
                }
                result = default;
                return false;
            }
            finally
            {
                manualResetEvent.Dispose();
                waitObject.TryRemove(key, out _);
                manualResetEvents.TryRemove(key, out _);
            }
        }


        /// <summary>
        /// 发送结果通知
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Notify(K key, T value)
        {
            if (manualResetEvents.TryGetValue(key, out var manualReset))
            {
                waitObject.TryAdd(key, value);
                manualReset.Set();
            }
        }

    }

    public class NotifyHandler<T> : NotifyHandler<string, T>
    {

    }
}
